﻿// ********************************************************************
//  文件名: MyUdpClient.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-19
// 
//  修改历史:
// ********************************************************************

using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MyApp;

public class MyUdpClient
{
    static UdpClient _client;
    static IPEndPoint _serverEndPoint;
    public static void Enter()
    {
        _client = new UdpClient(0);//随机给自己分配一个端口
        _serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324);
        //_client.Connect(_serverEndPoint); 不用绑定
        
        var receiveTh = new Thread(ReceiveLogic);
        receiveTh.IsBackground = true;
        receiveTh.Start();
        var sendTh = new Thread(SendLogic);
        sendTh.IsBackground = true;
        sendTh.Start();
    }

    static void ReceiveLogic()
    {
        while (true)
        {
            try
            {
                // Receive response from server
                byte[] receivedData = _client.Receive(ref _serverEndPoint);
                string receivedMessage = Encoding.UTF8.GetString(receivedData);

                Console.WriteLine($"Message received from server: {receivedMessage}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
    
    static void SendLogic()
    {
        byte[] sendData = new byte[1024];
        while (true)
        {
            string? message = Console.ReadLine();
            
            try
            {
                // Send message to server
                for (int i = 0; i < 10; i++)
                {
                    int dataCount = Encoding.UTF8.GetBytes(message + "[" + i, sendData);
                    _client.Send(sendData, dataCount, _serverEndPoint);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}